package com.ikas.autumn.iec104.module.protocol.handler;

import com.ikas.autumn.iec104.common.enums.BaseEnum;
import com.ikas.autumn.iec104.module.protocol.enums.ProtocolEnum;
import org.reflections.Reflections;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;

/**
 * 协议处理策略工厂
 *
 * @author fc
 */
public class ProtocolHandlerFactory {
    private ProtocolHandlerFactory() {
    }
    /**
     * 策略池
     */
    private static final Map<ProtocolEnum, ProtocolHandler> POOL = new HashMap<>();

    /**
     * 加载所有协议处理类
     * @author fc
     */
    static {
        // 扫描ProtocolHandler所在的包
        Reflections reflections = new Reflections(ProtocolHandler.class.getPackage().getName());
        // 获取包下面所有ProtocolHandler实现类
        Set<Class<? extends ProtocolHandler>> implClass = reflections.getSubTypesOf(ProtocolHandler.class);

        for(Class<? extends ProtocolHandler> aClass : implClass){
            ProtocolHandler protocolHandler = null;
            try {
                protocolHandler = aClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            POOL.put(protocolHandler.key(), protocolHandler);
        }
    }



    /**
     * 根据类型获取策略
     * @param key 类型标识
     * @return ProtocolHandler
     * @author fc
     */
    public static Optional<ProtocolHandler> get(String key) {
        Optional<ProtocolEnum> optional = BaseEnum.of(ProtocolEnum.class, key);
        return optional.map(POOL::get);
    }


    /**
     * 根据类型获取策略
     * @return ProtocolHandler
     * @author fc
     */
    public static void list(Consumer<ProtocolHandler> consumer) {
        POOL.values().forEach(consumer);
    }


}
